//=================================================
// nabton.c
// 2014-12-28
//=================================================
// sprintf(sys,"wget -q -O download.nab \"http://test.nabton.com/nabServer/server.php?user=%d&id=%d&cpar=%d&year=%d&month=%d&day=%d&hour=%d&min=%d&sec=%d&pulse=%d&pow=%.2f&data=",g_user,g_id,g_cpar,ltime->tm_year,ltime->tm_mon,ltime->tm_mday,ltime->tm_hour,ltime->tm_min,ltime->tm_sec,g_pulse,x);
//=================================================
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <termios.h>


//#define MODEM "/dev/ttyACM0"
#define BAUDRATE B9600   
#define NABTON_DATA 1
#define NABTON_DATA_ACK 2

// Nabton Control Protocol
#define ON_NABTON_SID    1
#define ON_HEARTBEAT     2
#define ON_STEPPER_CTRL  4

// Arduino Control Protocol
#define ON_HB_VAL        2
#define ON_HB_UNIT       3
#define ON_STEPPER_DIR   4
#define ON_STEPPER_STEPS 5
#define ON_STEPPER_SPEED 6

#define SILENT 0


struct termios tio;
int  tty_fd, flags;

int  arh_logged_in = 0;    // logged out
int  arh_logging   = 0;    // logging off
//int  arh_baudrate  = B9600;
//char arh_modem[24];
char res[512];
// Configuration parameters
char arh_url[80];
char arh_dev[80];
int  arh_id     =  7777;
int  arh_delay  = 12; // Number of 10sec between data report
int nb_sid = 0;
int nb_hb = 10;
int nb_hb_unit = 1;
int nb_stepper_dir = 0;  // 1=CW, 2=CCW
int nb_stepper_steps = 0;
int nb_mid;
int on[100];
int value[100];
int  connectToWebServer = 0;
float nb_data  = 0.0;
int nb_command;
char msg[200];
//===============================
int toString(char a[]) {
  int c, sign, offset, n;
 
  if (a[0] == '-') {  // Handle negative integers
    sign = -1;
  }
 
  if (sign == -1) {  // Set starting position to convert
    offset = 1;
  }
  else {
    offset = 0;
  }
 
  n = 0;
 
  for (c = offset; a[c] != '\0'; c++) {
    n = n * 10 + a[c] - '0';
  }
 
  if (sign == -1) {
    n = -n;
  }
 
  return n;
}

//===============================
void sendAckArduino(int n,char *msg)
{
  unsigned char c='D';
  unsigned char z='D';
  int i;

  for(i=0;i<n;i++)
    {
      z = msg[i];
      if(SILENT==0)printf("i=%d send %d\n ",i,(int)z);
      write(tty_fd,&z,1);  // Write Serial data to Arduino
    }
  //tcsetattr(tty_fd, TCSAFLUSH, &tio);
  return;
}

//===============================
int recArduino()
{
  unsigned char c='D';
  unsigned char z='D';
  int i,temp1,temp2;
  char inres[90];

     
  int nn = 0;
  while (c != ';')
    {
      if (read(tty_fd,&c,1)>0) // Read Serial data from Arduino
        {
          if(SILENT==0)printf("%c",c);
          inres[nn] = c;
          nn++;
        }
    }
  c = ' ';
  inres[nn-1] = '\0';
  //tcsetattr(tty_fd, TCSAFLUSH, &tio);      
  //printf("](%s)\n",inres); 
  if(SILENT==0)printf("Received from Arduino: (%s) n=%d\n",inres,nn);
  sscanf(inres,"%d",&nb_mid);
  if(nb_mid == NABTON_DATA)
  {
    sscanf(inres,"%d %d %f",&nb_mid,&nb_sid,&nb_data);
    if(SILENT==0)printf("mid=%d sid=%d data=%f\n", nb_mid, nb_sid, nb_data);
    return(1);
  }

  return(0);
}
//===============================
void delay(int t)
{
  t = t*1000; // convert to ms
  usleep(t);
}

//===============================
void processArh()
//===============================
{
  FILE  *in;
  char  line[128],key[32];
  int   itemp,k,val1,val2,val3,i,answer = 0;
   
  in = fopen("download.nab","r");
  if(in == NULL)
    {
      printf("Unable to open download.nab");
    }
  else
    {
      for(i=0;i<100;i++)on[i] = 0;
      while (fgets(line,sizeof line,in) != NULL)
        {
		  printf("%s",line);
          sscanf(line,"%s",key);
          if(strstr(key,"NABTON_SID")    != NULL) 
          {
			  sscanf(line,"%s %d",key,&val1);
			  answer = 1; 
			  nb_sid = val1;
		  }
          if(strstr(key,"HEARTBEAT")     != NULL) 
          {
			  sscanf(line,"%s %d %d",key,&val1,&val2);
			  on[ON_HB_VAL]  = 1; 
			  on[ON_HB_UNIT]  = 1; 
			  value[ON_HB_VAL]  = val1;
			  value[ON_HB_UNIT] = val2;   
	      }
          if(strstr(key,"STEPPER_CTRL")  != NULL) 
          {
			  sscanf(line,"%s %d %d %d",key,&val1,&val2,&val3);
			  on[ON_STEPPER_DIR] = 1; 
			  on[ON_STEPPER_STEPS] = 1; 
			  on[ON_STEPPER_SPEED] = 1; 
			  value[ON_STEPPER_DIR] = val1;
			  value[ON_STEPPER_STEPS] = val2;
			  value[ON_STEPPER_SPEED] = val3;
		  }
        }
       if(answer == 1)
       {
		  if(SILENT==0)printf("Server Message sid=: %d\n",nb_sid);
          msg[0] = 2;
          msg[1] = (nb_sid&0xff);
          itemp = nb_sid >> 8;
          msg[2] = (itemp&0xff);
          k = 3;
          for(i=0;i<100;i++)
          {
		      if(on[i] != 0)
		      {
				 if(SILENT==0)printf("MSG:%d Value:%d\n",i,value[i]);
			     msg[k] = i;
			     msg[k+1] = value[i];
			     k = k + 2;
		      }
	      }
	      msg[k] = 0;
	      if(SILENT==0)printf("Total Message size: %d\n",k);
	      k++;
          sendAckArduino(k,msg);
       }
       else
        if(SILENT==0)printf("No Server Message\n");
       fclose(in);   
       system("rm -f download.nab");  
    }

 }  

//===============================
void readConfig()
//===============================
{
  FILE  *in,*out;
  char  line[128];
  char temps[12];

  in = fopen("config.nab","r");
  if(in == NULL)
    {
      strcpy(arh_url,   "213.67.148.190/nabton/NDSServer/NDSCollector.php");
      strcpy(arh_dev,   "/dev/ttyACM0");
      
      if(SILENT==0)printf("Create config file\n");
      out = fopen("config.nab","w");
      fprintf(out,"URL:  %s\n",arh_url);
      fclose(out);
    }
  else
    {
      if(SILENT==0)printf("Open config file\n");
      while (fgets(line,sizeof line,in) != NULL)
          {
            if(strstr(line,"URL:") != NULL)sscanf(line,"%s %s",temps,arh_url);
          }
      fclose(in);
    } 
}

//===============================
void readDeviceName()
//===============================
{
  FILE  *in,*out;
  int n = 0;
  char  line[128];
  char  temps[12];

  system("ls /dev | grep ACM > device.nab"); 
  in = fopen("device.nab","r");
  if(in == NULL)
    {
      printf("No ACM device information file\n");
    }
  else
    {
      while (fgets(line,sizeof line,in) != NULL)
	{ 
          n++;
	  if(strstr(line,"ttyACM") != NULL)sscanf(line,"%s",temps);
	  strcpy(arh_dev,"/dev/");
	  strcat(arh_dev,temps);
	}
      fclose(in);
    }

  if(n > 1)printf("Multiple ACM devices found - check Arduino connection\n");

  if(n == 0)
  {
  system("ls /dev | grep USB > device.nab"); 
  in = fopen("device.nab","r");
  if(in == NULL)
    {
      printf("No USB device information file\n");
    }
  else
    {
      while (fgets(line,sizeof line,in) != NULL)
	{ 
      n++;
	  if(strstr(line,"ttyUSB") != NULL)sscanf(line,"%s",temps);
	  strcpy(arh_dev,"/dev/");
	  strcat(arh_dev,temps);
	}
      fclose(in);
    }

  if(n > 1)printf("Multiple USB devices found - check Arduino connection\n");
  }
  
}
//===============================
void readIpAddress(char *ips)
//===============================
{
  FILE  *in;
  char  line[128];
  char  temps[12];
  int   net = 0,netType=0;

  system("ifconfig > ipaddress.nab");
  delay(1000);
  in = fopen("ipaddress.nab","r");
  if(SILENT==0)printf("Open ip file\n");
  strcpy(ips,"no ip found");
  while (fgets(line,sizeof line,in) != NULL)
  { 
          if(strstr(line,"wlan") != NULL)
          {
             net = 1; //wlan
          }
          if(strstr(line,"eth") != NULL)
          {
             net = 2; //eth
          }
          if(strstr(line,"Loopback") != NULL)
          {
             net = 3; //lo
          }
          if(strstr(line,"inet addr:") != NULL)
          {
             if(net != 3)
             {
               netType = net;
               sscanf(line,"%s %s",temps,ips);
             }
          }
  }
  fclose(in);
  if(SILENT==0)printf("%d %s\n",netType,ips);
  return;
}
//===============================
int main(int argc,char** argv)
//===============================
{   
  int i,value = 9999;
  time_t tm;
  struct tm *ltime;

  char res[120],com[120],sys[240],ip[80];
    
  readConfig();
  readIpAddress(ip);
  readDeviceName();

  if(SILENT==0)printf("URL.........: %s\n",arh_url);
  if(SILENT==0)printf("Device......: %s\n",arh_dev);
  if(SILENT==0)printf("IP..........: %s\n",ip);

 
  //printf("ARDUINO CONNECTION\n");
  memset(&tio,0,sizeof(tio));
  tio.c_iflag=0;
  tio.c_oflag=0;
  tio.c_cflag=CS8|CREAD|CLOCAL;  // 8n1, see termios.h for more information
  tio.c_lflag=0;
  tio.c_cc[VMIN]=1;
  tio.c_cc[VTIME]=5;
  if((tty_fd = open(arh_dev , O_RDWR | O_NONBLOCK)) == -1)
  {
        if(SILENT==0)printf("Waiting for Arduino connection...\n"); 
  }
  else
  {
        if(SILENT==0)printf("Connected to Arduino %s\n",arh_dev); 
        cfsetospeed(&tio,BAUDRATE);    
        cfsetispeed(&tio,BAUDRATE);      
        tcsetattr(tty_fd,TCSANOW,&tio);
        tcsetattr(tty_fd, TCSAFLUSH, &tio);
  }            
      
  for(i=0;i<100;i++)on[i] = 0;
  while(1)
  {
      int go = 0;
      go = recArduino();
 
      if(go == 1)
      {
         sprintf(sys,"wget -q -O download.nab \"http://%s?mid=%d&sid=%d&data=%.2f\"",arh_url,nb_mid,nb_sid,nb_data);
         if(SILENT==0)printf("%s\n",sys);
         system(sys);
         processArh();
      }
  }
           
  close(tty_fd);
  return EXIT_SUCCESS;
}
